package com.walming.generator.common.validator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.List;

/**
 * @author walming
 * @date 2020-11-25 13:58
 */
public class ListStringValueValidator implements ConstraintValidator<ListStringValue, List<String>> {

    private ListStringValue listStringValue;

    /**
     * 初始化 可以获得当前注解的所有属性
     */
    @Override
    public void initialize(ListStringValue listStringValue) {
        this.listStringValue = listStringValue;
    }

    /**
     * 进行约束验证的主体方法
     *
     * @param stringList 标识验证参数的具体实例
     * @param context    约束执行的上下文环境
     */
    @Override
    public boolean isValid(List<String> stringList, ConstraintValidatorContext context) {
        if (stringList == null || listStringValue.list().length <= 0) {
            return true;
        }
        boolean flag = false;
        StringBuilder message = new StringBuilder();
        List<String> range = Arrays.asList(listStringValue.list());
        for (String i : stringList) {
            if (!range.contains(i)) {
                if (message.length() > 0) {
                    message.append(",");
                }
                message.append(i);
            }
        }
        if (message.length() == 0) {
            flag = true;
        }
        // 重置错误提示信息 message
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate("数据{" + message + "}不在接口定义的集合内").addConstraintViolation();

        return flag;
    }

}
